package com.huizluo.module3.list;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class ListStore implements Store{

    private List<Item> db = new ArrayList<Item>();
    private HashMap<Integer,Integer> index = new HashMap<>();


    @Override
    public boolean Add(Item item) throws Exception {
        if (this.index.get(item.ID) !=null){
            throw new Exception("same ID " + item.ID + " exist");
        }
        this.db.add(item);
        this.index.put(item.ID,this.db.indexOf(item));
        return true;
    }

    @Override
    public Item Find(Integer Id) throws Exception {
        Integer index = this.index.get(Id);
        if (index == null){
            throw new Exception("ID " + Id + " can not found");
        }
        return this.db.get(index);
    }

    @Override
    public boolean Remove(Item t) throws Exception {
        Integer index = this.index.get(t.ID);
        if (index == null){
            throw new Exception("ID " + t.ID + " can not found");
        }

        this.db.remove(index.intValue());
        this.index.remove(t.ID);
        return true;
    }

    @Override
    public boolean Update(Item t) throws Exception {
        Integer index = this.index.get(t.ID);
        if (index == null){
            throw new Exception("ID " + t.ID + " can not found");
        }
        this.db.set(index,t);
        return true;
    }

    @Override
    public Item[] List() {
        int size = this.db.size();
        Item[] items = new Item[size];
        for(int i=0;i<this.db.size();i++){
        items[i] = this.db.get(i);
    }
        return items;
}


}
